﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using SqlSugarCoreDemo.DBSqlSugar;
using SqlSugarCoreDemo.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace SqlSugarCoreDemo.Middlewares
{
    public class RecordAccessLogsMildd
    {
        private readonly RequestDelegate _next;
        private readonly IWebHostEnvironment _env;
        /// <summary>
        /// 构造函数
        /// </summary>
        public RecordAccessLogsMildd(RequestDelegate next, IWebHostEnvironment env)
        {
            _next = next;
            _env = env;
        }

        /// <summary>
        /// 管道数据处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context, IUnitOfWork unitOfWork)
        {
            SqlSugarClient _dbBase = unitOfWork.GetDbClient();
            try
            {
                HttpRequest request = context.Request;
                

                #region 应用与验签======================================
                //开启计时器
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                //设置默认响应内容类型
                context.Response.Headers.Add("Content-Type", new Microsoft.Extensions.Primitives.StringValues("application/json"));

                //执行下一个中间件
                await _next(context);
                #endregion

                //响应完成执行
                context.Response.OnCompleted(() =>
                {
                    //记录应用访问日志
                    SysAppsAccessLog appsReceiveLog =  new SysAppsAccessLog()
                    {
                        appId = "appId",
                        requestTime = DateTime.Now,
                        responseTime = null,
                        loadSecond = 0,
                        clientInfo = "clientInfo",
                    }; ;
                    //响应完成记录时间和存入日志
                    appsReceiveLog.responseTime = DateTime.Now;
                    //访问耗时
                    stopwatch.Stop();
                    appsReceiveLog.loadSecond = (stopwatch.ElapsedMilliseconds/ 1000);

                    1、SqlServer高并发时（Jmeter用户100位，访问: http://localhost:1000/login 部分出现The connection is closed）
                    //2、Sqlite 正常无问题
                    _dbBase.GetConnection(DBSqlSugar.DBTenantIds.Main).Insertable(appsReceiveLog).SplitTable().ExecuteReturnSnowflakeIdAsync();

                    Console.WriteLine("访问成功！");

                    return Task.CompletedTask;
                });

            }
            catch (Exception ee)
            {
                //出现错误，记录日志
                Console.WriteLine("Middlewares Error：" + ee.Message);
                
                await context.Response.WriteAsync("系统请求出错，请稍后再试");
                return;
            }
        }
    }
}
